package cn.ryanpenn.es.ms.gathering.service.impl;

import cn.ryanpenn.es.ms.gathering.service.CityServiceClient;
import cn.ryanpenn.es.ms.gathering.service.GatheringService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * GatheringServiceImpl
 *
 * @author pennryan
 */
@Service
public class GatheringServiceImpl implements GatheringService {

    private final String WEATHER_BYKEY_API = "http://wthrcdn.etouch.cn/weather_mini?citykey=";
    /**
     * 缓存过期时间: 30分钟
     */
    private final int TIMEOUT = 30 * 60;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    OkHttpClient okHttpClient;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    CityServiceClient cityService;

    @Override
    public void gatheringData() {
        if (cityService != null) {
            cityService.getCityList().forEach(city -> {
                syncData(WEATHER_BYKEY_API + city.getCode());
            });
        }
    }

    /**
     * 从网络下载数据,然后保存到redis中
     * @param url
     */
    private void syncData(String url) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            ResponseBody body = response.body();
            if (body != null) {
                String bodyStr = body.string();
                JsonNode node = new ObjectMapper().readTree(bodyStr);
                if (node != null && node.has("data")) {
                    ops.set(url, bodyStr, TIMEOUT, TimeUnit.SECONDS);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
